﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Infragistics.WebUI.WebSchedule;

using TBA.PGB.DAO.DBEntity;
using TBA.PGB.Business;

public partial class secure_zk_PGB_Assignment_AddIB_AddIBInformations : AZRLiveBaseWebPage
{
    private System.IFormatProvider frmt;

    protected void Page_Load(object sender, EventArgs e)
    {
        nav = (Navigatie)Session["Navigatie"];

        base.RequiredRole = "pgb_overview";
        base.RunSecurityCheck();

        frmt = new System.Globalization.CultureInfo("de-DE", true);

        if (!IsPostBack)
        {
            LoadStepPage(StepType.Step2);
        }

        if (Panel_Step4.Visible)
        {
            LoadStep4SourceDatas();
        }
    }

    #region private method
    /// <summary>
    /// The list of step page
    /// </summary>
    private enum StepType
    {
        Step2,
        Step3,
        Step4
    }

    /// <summary>
    /// Load the step by StepType
    /// </summary>
    /// <param name="st"></param>
    private void LoadStepPage(StepType st)
    {
        try
        {
            switch (st)
            {
                case StepType.Step2:
                    Panel_Step2.Visible = true;
                    Panel_Step3.Visible = false;
                    Panel_Step4.Visible = false;

                    LoadStep2SourceDatas();
                    break;
                case StepType.Step3:
                    Panel_Step2.Visible = false;
                    Panel_Step3.Visible = true;
                    Panel_Step4.Visible = false;

                    LoadStep3SourceDatas();
                    break;
                case StepType.Step4:
                    Panel_Step2.Visible = false;
                    Panel_Step3.Visible = false;
                    Panel_Step4.Visible = true;

                    LoadStep4SourceDatas();
                    break;
                default:
                    Panel_Step2.Visible = true;
                    Panel_Step3.Visible = false;
                    Panel_Step4.Visible = false;
                    break;
            }
        }
        catch (Exception ex)
        {
            throw ex;
            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Error", "parent.resultaat.location.href = '../../../../CustomErrors/GenericErrorPage.aspx'", true);
        }
    }

    /// <summary>
    /// Bind the source datas of dropdownlists
    /// </summary>
    /// <param name="datasource"></param>
    /// <param name="ddlist"></param>
    private void bindLists(Dictionary<String, String> datasource, DropDownList ddlist)
    {
        ddlist.Items.Clear();

        foreach (String key in datasource.Keys)
        {
            ddlist.Items.Add(new ListItem(datasource[key], key));
        }
    }

    private void SetNavigatie(eHoofdNavigatie hoofdNavigatie)
    {
        nav.HoofdNavigatie = hoofdNavigatie;
        Session["Navigatie"] = nav;
    }
    #endregion

    #region Step 2

    #region Load Step 2 Datas
    private void LoadStep2SourceDatas()
    {
        LoadDefaultValues();
        LoadClientandAddress();
    }

    private void LoadDefaultValues()
    {
        Naamcode1.Waarde = "1";
        Naamcode3.Waarde = "1";
        Geslacht.Waarde = "1";
        Leefeenheid.Waarde = "9";

        codeland.Waarde = "NL";
    }

    private void LoadClientandAddress()
    {
        //Load the basic client informations
        BSN.Enabled = false;
        BSN.Waarde = (Int64.Parse(nav.Client.Burgerservicenummer) == 0 ? String.Empty : nav.Client.Burgerservicenummer);

        ddl_ClientType.Enabled = nav.Client.ClientID == new Guid() ? true : false;

        if (nav.Client.ClientID != new Guid())
        {
            //Client can be obtained from the navigation object.
            Client client = ClientManager.GetClient(nav.Client.ClientID, nav.User.ConnString);
            string artikel60dat = IndicatiebesluitManager.GetArtikel60Datum(nav.Client.GeselecteerdIndicatiebesluitID, nav.User.ConnString);

            ddl_ClientType.SelectedValue = Convert.ToInt32(client.PGBClientType).ToString();
            Naam1.Waarde = client.Naam01;
            Voorvoegsel1.Waarde = client.Voorvoegsel01;
            Voorletters.Waarde = client.Voorletters;
            Naamcode1.Waarde = client.Naamcode01;
            Naam2.Waarde = client.Naam02;
            Voorvoegsel2.Waarde = client.Voorvoegsel02;
            Naamcode2.Waarde = client.Naamcode02;
            Naamcode3.Waarde = (client.Naamcode03 == "1" ? "1" : client.Naamcode03);
            Geboortedatum.Waarde = client.Geboortedatum;
            Geslacht.Waarde = client.Geslacht.Code;
            Burgerlijkestaat.Waarde = client.Burgerlijkestaat.Code;
            //UZOVInummer.Waarde = client.UZOVInummer;
            Verzekerdenummer.Waarde = client.Verzekerdennummer;
            Leefeenheid.Waarde = ((client.Leefeenheid.Code) == String.Empty ? "NL" : client.Leefeenheid.Code);

            //Load the address informations of the client
            LoadAddress(client);
        }
    }

    /// <summary>
    /// Load the address informations of the client
    /// </summary>
    /// <param name="client"></param>
    private void LoadAddress(Client client)
    {
        Adres adres = AddressHandler.getAdredByClientID(nav.Client.ClientID, nav.User.ConnString);

        if (adres != null)
        {
            HF_AddressID.Value = adres.AdresID.ToString();
            soortadres.Waarde = adres.SoortAdres.Code;

            codeland.Waarde = (adres.CodeLand == "NL" ? "NL" : adres.CodeLand);
            huisnummer.Waarde = (adres.Huisnummer == 0 ? String.Empty : adres.Huisnummer.ToString());
            huisnummertoevoeging.Waarde = adres.HuisnummerToevoeging;
            postcode.Waarde = adres.Postcode;

            straatnaam.Waarde = adres.Straatnaam;
            telefoonnummer1.Waarde = adres.Telefoonnummer01;
            woonplaats.Waarde = adres.WoonplaatsNaam;
        }

        ViewState["OrignalAddress"] = adres;

        nav.Client = client;
    }

    private void LoadAgeDuration()
    {
        ///Set the duration of birthday by the Client Type
        ///BJZ: younger than 18
        if (ddl_ClientType.SelectedValue == "1")
        {
            Geboortedatum.CustomerMaxDate = DateTime.Now;
            Geboortedatum.CustomerMinDate = DateTime.Now.AddYears(-18);
        }
        else if (ddl_ClientType.SelectedValue == "2")
        {
            Geboortedatum.CustomerMaxDate = DateTime.Now.AddYears(-18);
            Geboortedatum.CustomerMinDate = new DateTime(1753, 1, 1);
        }
    }

    private void ChangeStep2InputsStatus(Boolean status)
    {
        //Client informations
        ddl_ClientType.Enabled = status;
        Naam1.Enabled = status;
        Voorvoegsel1.Enabled = status;
        Voorletters.Enabled = status;
        Naamcode1.Enabled = status;
        Naam2.Enabled = status;
        Voorvoegsel2.Enabled = status;
        Naamcode2.Enabled = status;
        Naamcode3.Enabled = status;
        Geslacht.Enabled = status;
        Geboortedatum.Enabled = status;
        Burgerlijkestaat.Enabled = status;
        Verzekerdenummer.Enabled = status;
        Leefeenheid.Enabled = status;

        //Address informations
        soortadres.Enabled = status;
        huisnummer.Enabled = status;
        huisnummertoevoeging.Enabled = status;
        postcode.Enabled = status;
        straatnaam.Enabled = status;
        woonplaats.Enabled = status;
        codeland.Enabled = status;
        telefoonnummer1.Enabled = status;
    }
    #endregion

    #region Step 2 Buttons Actions
    protected void clientInfo_btn_Cancel_Click(object sender, EventArgs e)
    {
    }

    protected void ddl_ClientType_SelectedIndexChanged(object sender, EventArgs e)
    {
        Geboortedatum.Waarde = String.Empty;

        if (((DropDownList)sender).SelectedValue == "1")
        {
            Geboortedatum.CustomerMaxDate = DateTime.Now;
            Geboortedatum.CustomerMinDate = DateTime.Now.AddYears(-18);
        }
        else if (((DropDownList)sender).SelectedValue == "2")
        {
            Geboortedatum.CustomerMaxDate = DateTime.Now.AddYears(-18);
            Geboortedatum.CustomerMinDate = new DateTime(1753, 1, 1);
        }
    }

    private void SaveDatasofStep2()
    {
        //Save Client Informations
        nav.Client.PGBClientType = (ClientType)Convert.ToInt32(ddl_ClientType.SelectedValue.Trim().ToString());

        //nav.Client.ClientID = nav.Client.ClientID == new Guid() ? Guid.NewGuid() : nav.Client.ClientID;
        nav.Client.Naam01 = Naam1.Waarde.ToString().Trim();
        nav.Client.Voorvoegsel01 = Voorvoegsel1.Waarde.ToString().Trim();
        nav.Client.Voorletters = Voorletters.Waarde.ToString().Trim();
        nav.Client.Naamcode01 = Naamcode1.Waarde.ToString().Trim();
        nav.Client.Naam02 = Naam2.Waarde.ToString().Trim();
        nav.Client.Voorvoegsel02 = Voorvoegsel2.Waarde.ToString().Trim();
        nav.Client.Naamcode02 = Naamcode2.Waarde.ToString().Trim();
        nav.Client.Naamcode03 = Naamcode3.Waarde.ToString().Trim();
        nav.Client.Geslacht = new CodelijstGegeven(Geslacht.Waarde);
        nav.Client.Geboortedatum = (Geboortedatum.Waarde == "" ? "0" : DateTime.ParseExact(Geboortedatum.Waarde, "yyyyMMdd", frmt).ToString("dd-MM-yyyy"));

        nav.Client.Burgerlijkestaat = new CodelijstGegeven(Burgerlijkestaat.Waarde);
        nav.Client.Verzekerdennummer = Verzekerdenummer.Waarde.ToString().Trim();
        nav.Client.Leefeenheid = new CodelijstGegeven(Leefeenheid.Waarde);
        nav.Client.MutatieDatum = DateTime.Now.ToString("dd-MM-yyyy");

        nav.Client.ZorgkantoorID = new Guid(nav.User.ZorgkantoorID);
    }

    protected void clientInfo_btn_Previous_Click(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Manually add IB", "parent.resultaat.location.href = 'CheckBSN.aspx'", true);
        SetNavigatie(eHoofdNavigatie.PGBToevoegenClienIB);
    }

    protected void clientInfo_btn_Next_Click(object sender, EventArgs e)
    {
        SaveDatasofStep2();
        LoadStepPage(StepType.Step3);
    }
    #endregion

    #endregion

    #region Step 3

    #region Load Step 3 Datas
    private void LoadStep3SourceDatas()
    {
        LoadStep3TextBox();
        LoadExZZPCodes();
        LoadIndicationDDLists();
    }

    private void LoadStep3TextBox()
    {
        txt_BSN.Text = nav.Client.Burgerservicenummer;

        if (ddl_besluitnummer.SelectedValue == "[Geen]")
        {
            txt_Aanvraagnummer.Text = String.Empty;
            WDC_IndicationDate.Value = String.Empty;
            WDC_ReceiveDate.Value = String.Empty;
            WDC_StartDate.Value = String.Empty;
            WDC_EndDate.Value = String.Empty;
        }
        else
        {
            LoadExistIndicationInfos(ddl_besluitnummer.SelectedValue, txt_besluitnummer.Visible);
        }

        WDC_IndicationDate.MaxDate = DateTime.Now;
        WDC_IndicationDate.MinDate = new DateTime(1753, 1, 1);

        WDC_ReceiveDate.MaxDate = DateTime.Now;
        WDC_ReceiveDate.MinDate = new DateTime(1753, 1, 1);

        WDC_StartDate.MinDate = new DateTime(2008, 1, 1);
        WDC_EndDate.MinDate = new DateTime(2008, 1, 1);
    }

    private void LoadExZZPCodes()
    {
        RFV_1stZZPEndDate.EnableClientScript = chk_AdditionalZZPs.Checked;
        RFV_2ndZZPStartCode.EnableClientScript = chk_AdditionalZZPs.Checked;

        tr_1stZZPDates.Visible = chk_AdditionalZZPs.Checked;
        tr_2ndZZP.Visible = chk_AdditionalZZPs.Checked;
        tr_2ndZZPDates.Visible = chk_AdditionalZZPs.Checked;

        if (chk_AdditionalZZPs.Checked)
        {
            validateBesluitnummer(chk_AdditionalZZPs.Checked);
            validateAanvraagnummer(chk_AdditionalZZPs.Checked);

            bindLists(IBManuallyHandler.GetZZPCodes(
                
                nav.User.ConnString),
            ddl_2ndZZPCode);

            ddl_2ndZZPCode.Items.Add("[Geen]");
            ddl_2ndZZPCode.SelectedValue = "[Geen]";
        }
    }

    private void validateAanvraagnummer(bool Status)
    {
        RFV_Aanvraagnummer.EnableClientScript = Status;
        REV_Aanvraagnummer.EnableClientScript = Status;
    }

    private void LoadIndicationDDLists()
    {
        //Bind Care offices datas
        switch (nav.Client.PGBClientType)
        {
            case ClientType.MANUALLY:
                lbl_OfficeList.InnerText = "Hoofdkantoor BJZ";
                lbl_Aanvraagnummer.Visible = false;
                txt_Aanvraagnummer.Visible = false;
                bindLists(IBManuallyHandler.GetBJZOffices(nav.User.ConnString), ddl_Office);
                break;

            case ClientType.AZRLive:
                lbl_OfficeList.InnerText = "Code Indicatieorgaan";
                lbl_Aanvraagnummer.Visible = true;
                txt_Aanvraagnummer.Visible = true;

                validateAanvraagnummer(lbl_OfficeList.InnerText == "Code Indicatieorgaan" ? true : false);
                bindLists(IBManuallyHandler.GetCIZOffices(nav.User.ConnString), ddl_Office);
                break;

            default:
                break;
        }

        //Bind basis datas
        bindLists(IBManuallyHandler.GetGrondslags(null, nav.User.ConnString), ddl_1grondslag);
        bindLists(IBManuallyHandler.GetGrondslags(null, nav.User.ConnString), ddl_2grondslag);

        //Bind ZZP code datas
        bindLists(IBManuallyHandler.GetZZPCodes(nav.User.ConnString), ddl_zzpCode);
        ddl_zzpCode.Items.Add("[Geen]");
        ddl_zzpCode.SelectedValue = "[Geen]";

        if (chk_AdditionalZZPs.Checked)
        {
            bindLists(IBManuallyHandler.GetZZPCodes(nav.User.ConnString), ddl_2ndZZPCode);
            ddl_2ndZZPCode.Items.Add("[Geen]");
            ddl_2ndZZPCode.SelectedValue = "[Geen]";
        }

        //Bind indication number datas
        bindLists(IBManuallyHandler.GetIndicationNumbers(txt_BSN.Text.ToString().Trim(), nav.User.ConnString), ddl_besluitnummer);
        ddl_besluitnummer.Items.Add("[Geen]");
        ddl_besluitnummer.SelectedValue = "[Geen]";
    }

    private void ChangeStep3InputsStatus(Boolean status)
    {
        ddl_Office.Enabled = status;
        ddl_besluitnummer.Enabled = status;
        txt_besluitnummer.Enabled = status;
        txt_Aanvraagnummer.Enabled = status;
        WDC_ReceiveDate.Enabled = status;
        WDC_IndicationDate.Enabled = status;
        WDC_StartDate.Enabled = status;
        WDC_EndDate.Enabled = status;
        ddl_1grondslag.Enabled = status;
        ddl_2grondslag.Enabled = status;
        ddl_zzpCode.Enabled = status;
        chk_AdditionalZZPs.Enabled = status;

        if (chk_AdditionalZZPs.Checked)
        {
            WDC_1stZZPEndDate.Enabled = status;
            ddl_2ndZZPCode.Enabled = status;
            WDC_2ndZZPStartCode.Enabled = status;
        }
    }
    #endregion

    #region Validated Step 3 Datas
    private void validateGrondslag(DropDownList ddlList, DropDownList ddlList_selected, String original_SV)
    {
        bindLists(IBManuallyHandler.GetGrondslags(ddlList_selected.SelectedValue, nav.User.ConnString), ddlList);

        if (ddlList.Items.FindByValue(original_SV) != null)
        {
            ddlList.SelectedValue = original_SV;
        }
    }

    private void validateZZP(DropDownList ddlList, DropDownList ddlList_selected, String original_ZZPCode)
    {
        bindLists(IBManuallyHandler.GetZZPCodes(nav.User.ConnString), ddlList);

        if (ddlList.Items.FindByValue(original_ZZPCode) != null)
        {
            ddlList.SelectedValue = original_ZZPCode;
        }
    }

    private void validateBesluitnummer(Boolean status)
    {
        REV_Besluitnummer.EnableClientScript = status;
        RFV_Besluitnummer.EnableClientScript = status;
    }

    private void LoadStep3Durations()
    {
        //Load the duration of ZZPCodes'
        WDC_1stZZPEndDate.MinDate = DateTime.Parse(WDC_StartDate.Value.ToString());
        WDC_2ndZZPStartCode.MinDate = DateTime.Parse(WDC_StartDate.Value.ToString());

        WDC_1stZZPEndDate.MaxDate = DateTime.Parse(WDC_EndDate.Value.ToString());
        WDC_2ndZZPStartCode.MaxDate = DateTime.Parse(WDC_EndDate.Value.ToString());

        if (chk_AdditionalZZPs.Checked)
        {
            //Load the Date_labels
            ltl_1stZZPStartDate.Text = DateTime.Parse(WDC_StartDate.Value.ToString()).ToShortDateString();
            ltl_2ndZZPEndDate.Text = DateTime.Parse(WDC_EndDate.Value.ToString()).ToShortDateString();
        }
    }
    #endregion

    #region Step 3 Dropdownlists(/DateChooser) Actions
    protected void ddl_1grondslag_SelectedIndexChanged(object sender, EventArgs e)
    {
        validateGrondslag(ddl_2grondslag, (DropDownList)sender, ddl_2grondslag.SelectedValue);
    }

    protected void ddl_2grondslag_SelectedIndexChanged(object sender, EventArgs e)
    {
        validateGrondslag(ddl_1grondslag, (DropDownList)sender, ddl_1grondslag.SelectedValue);
    }

    protected void ddl_zzpCode_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (chk_AdditionalZZPs.Checked)
        {
            validateZZP(ddl_2ndZZPCode, (DropDownList)sender, ddl_2ndZZPCode.SelectedValue);
        }
    }

    protected void ddl_2ndZZPCode_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (chk_AdditionalZZPs.Checked)
        {
            validateZZP(ddl_zzpCode, (DropDownList)sender, ddl_zzpCode.SelectedValue);
        }
    }

    protected void WDC_1stZZPEndDate_ValueChanged(object sender, WebDateChooser.WebDateChooserEventArgs e)
    {
        WDC_2ndZZPStartCode.Value = DateTime.Parse(((WebDateChooser)sender).Value.ToString()).AddDays(1);
    }

    protected void WDC_2ndZZPStartCode_ValueChanged(object sender, WebDateChooser.WebDateChooserEventArgs e)
    {
        WDC_1stZZPEndDate.Value = DateTime.Parse(((WebDateChooser)sender).Value.ToString()).AddDays(-1);
    }

    protected void WDC_StartDate_ValueChanged(object sender, WebDateChooser.WebDateChooserEventArgs e)
    {
        if (chk_AdditionalZZPs.Checked)
        {
            ltl_1stZZPStartDate.Text = DateTime.Parse(((WebDateChooser)sender).Value.ToString()).ToShortDateString();
        }
    }

    protected void WDC_EndDate_ValueChanged(object sender, WebDateChooser.WebDateChooserEventArgs e)
    {
        if (chk_AdditionalZZPs.Checked)
        {
            ltl_2ndZZPEndDate.Text = DateTime.Parse(((WebDateChooser)sender).Value.ToString()).ToShortDateString();
        }
    }

    protected void ddl_besluitnummer_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (((DropDownList)sender).SelectedValue == "[Geen]")
        {
            LoadExistIndicationInfos(String.Empty, true);
        }
        else
        {
            LoadExistIndicationInfos(((DropDownList)sender).SelectedValue, false);
            ChangeStep3InputsStatus(false);
        }
    }

    /// <summary>
    /// Load the existed indication's information by the ddl_besluitnummer
    /// </summary>
    /// <param name="indicationID"></param>
    /// <param name="inputsStatus"></param>
    private void LoadExistIndicationInfos(String indicationID, Boolean inputsStatus)
    {
        txt_besluitnummer.Visible = indicationID == String.Empty ? true : false;

        validateBesluitnummer(indicationID == String.Empty ? true : false);

        using (Indicatiebesluit indication = inputsStatus ? new Indicatiebesluit(new Guid()) :
            IBManuallyHandler.GetIndicationInfoByID(new Guid(indicationID.Trim()), nav.User.ConnString))
        {
            //if (indication.ReceiveDate != new DateTime())
            //{
            WDC_ReceiveDate.Value = indication.ReceiveDate;
            //}

            WDC_IndicationDate.Value = indication.DatumAfgifte;
            WDC_StartDate.Value = indication.DatumIngang;
            WDC_EndDate.Value = indication.DatumEindeGeldigheid;
            ddl_1grondslag.SelectedValue = indication.EersteGrondslag;
            ddl_2grondslag.SelectedValue = indication.TweedeGrondslag;
            txt_Aanvraagnummer.Text = txt_Aanvraagnummer.Visible ? indication.Aanvraagnummer : String.Empty;
        }
    }
    #endregion

    #region Step 3 Buttons Actions
    protected void chk_AdditionalZZPs_CheckedChanged(object sender, EventArgs e)
    {
        LoadExZZPCodes();
        LoadStep3Durations();
    }

    protected void indication_btn_Cancel_Click(object sender, EventArgs e)
    {

    }

    protected void indication_btn_Previous_Click(object sender, EventArgs e)
    {
        LoadStepPage(StepType.Step2);
    }

    private void SaveDatasofStep3()
    {
        Indicatiebesluit _pageIndication =
            new Indicatiebesluit(ddl_besluitnummer.SelectedValue == "[Geen]" ?
                Guid.NewGuid() : new Guid(ddl_besluitnummer.SelectedValue.Trim()));

        //_pageIndication.ClientID = nav.Client.ClientID;

        //_pageIndication.Indicatieorgaan = nav.Client.PGBClientType == ClientType.CIZ ? ddl_Office.SelectedValue : String.Empty;
        _pageIndication.Indicatieorgaan = ddl_Office.SelectedValue.Trim().ToString();
        //if (nav.Client.PGBClientType == "1" || nav.Client.PGBClientType == "2")
        //{
        //    _pageIndication.Indicatieorgaan = ddl_Office.SelectedValue;
        //}

        _pageIndication.Aanvraagnummer = txt_Aanvraagnummer.Visible ? txt_Aanvraagnummer.Text.ToString().Trim() : String.Empty;
        _pageIndication.Besluitnummer = ddl_besluitnummer.SelectedValue == "[Geen]" ? (txt_BSN.Text.ToString().Trim() == String.Empty ? String.Empty : txt_BSN.Text.ToString().Trim()) : ddl_besluitnummer.SelectedValue;
        _pageIndication.EersteGrondslag = ddl_1grondslag.SelectedValue;
        _pageIndication.TweedeGrondslag = ddl_2grondslag.SelectedValue;
        _pageIndication.DatumAfgifte = DateTime.Parse(WDC_IndicationDate.Value.ToString());
        _pageIndication.DatumIngang = DateTime.Parse(WDC_StartDate.Value.ToString());
        _pageIndication.DatumEindeGeldigheid = DateTime.Parse(WDC_EndDate.Value.ToString());
        _pageIndication.UpdatedBy = new Guid(nav.User.UserID);
        _pageIndication.Clientnummer = nav.Client.Clientnummer;
        //_pageIndication.AddingIB = (AddingIBWay)Convert.ToInt32(nav.Client.PGBClientType);

        _pageIndication.ZZP = ddl_zzpCode.SelectedValue;
        _pageIndication.ZZPStartDate = DateTime.Parse(WDC_StartDate.Value.ToString());
        _pageIndication.ZZPEndDate = chk_AdditionalZZPs.Checked ? DateTime.Parse(WDC_1stZZPEndDate.Value.ToString()) : DateTime.Parse(WDC_EndDate.Value.ToString());
        _pageIndication.SecondZZP = chk_AdditionalZZPs.Checked ? ddl_2ndZZPCode.SelectedValue : String.Empty;

        if (chk_AdditionalZZPs.Checked)
        {
            _pageIndication.SecondZZPStartDate = DateTime.Parse(WDC_2ndZZPStartCode.Value.ToString());
            _pageIndication.SecondZZPEndDate = DateTime.Parse(WDC_EndDate.Value.ToString());
        }

        _pageIndication.ReceiveDate = DateTime.Parse(WDC_ReceiveDate.Value.ToString());

        ViewState["PAGEINDICATION"] = _pageIndication;
    }

    protected void indication_btn_Next_Click(object sender, EventArgs e)
    {
        RFV_Besluitnummer.Enabled = txt_besluitnummer.Visible;
        validateAanvraagnummer(lbl_OfficeList.InnerText == "Code Indicatieorgaan" ? true : false);

        SaveDatasofStep3();

        ViewState["PageFuncs"] = IBManuallyHandler.GetFunctionsByIndicationID(
                    ((Indicatiebesluit)ViewState["PAGEINDICATION"]).IndicatiebesluitID, nav.User.ConnString);
        LoadStepPage(StepType.Step4);
    }
    #endregion

    #endregion

    secure_zk_PGB_Assignment_AddIB_FunctionInputs firstInputs = null;
    secure_zk_PGB_Assignment_AddIB_FunctionInputs secondInputs = null;
    #region Step 4
    private void LoadStep4SourceDatas()
    {
        using (Indicatiebesluit indi = (Indicatiebesluit)ViewState["PAGEINDICATION"])
        {
            firstZZP_head.Visible = chk_AdditionalZZPs.Checked;
            div_secondZZP.Visible = chk_AdditionalZZPs.Checked;

            Control firstZZPCodeInputs = Page.FindControl("firstFunctionPanel");
            firstInputs = (secure_zk_PGB_Assignment_AddIB_FunctionInputs)LoadControl("FunctionInputs.ascx");
            firstInputs.ID = "firstZZP";
            firstInputs.ZZPType = "firstZZP";
            firstInputs.ConnectionString = nav.User.ConnString;
            firstInputs.IndicationStatus = (ddl_besluitnummer.SelectedValue == "[Geen]" ? true : false);
            firstInputs.SourceIndication = (Indicatiebesluit)ViewState["PAGEINDICATION"];
            firstInputs.SourceFunctions = (List<ViewZTWFunction>)ViewState["PageFuncs"];
            firstInputs.SourceGridView = gv_Functions;
            firstInputs.SourceHiddenRowindex = HF_RowIndex;

            firstZZPCodeInputs.Controls.Add(firstInputs);
            firstInputs.LoadSourceDatas();

            if (chk_AdditionalZZPs.Checked)
            {
                Control secondZZPCodeInputs = Page.FindControl("secondFunctionPanel");
                secondInputs = (secure_zk_PGB_Assignment_AddIB_FunctionInputs)LoadControl("FunctionInputs.ascx");
                secondInputs.ID = "secondZZP";
                secondInputs.ZZPType = "secondZZP";
                secondInputs.ConnectionString = nav.User.ConnString;
                secondInputs.IndicationStatus = (ddl_besluitnummer.SelectedValue == "[Geen]" ? true : false);
                secondInputs.SourceIndication = (Indicatiebesluit)ViewState["PAGEINDICATION"];
                secondInputs.SourceFunctions = (List<ViewZTWFunction>)ViewState["PageFuncs"];
                secondInputs.SourceGridView = gv_Functions;

                secondZZPCodeInputs.Controls.Add(secondInputs);
                //secondInputs.LoadSourceDatas();
            }
        }
    }

    protected void gv_Functions_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && gv_Functions.Enabled)
        {
            for (int i = 1; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells[i].Attributes["OnClick"] = ClientScript.GetPostBackEventReference((GridView)sender, "Select$" + e.Row.RowIndex);
                e.Row.Cells[i].Style["cursor"] = "hand";

                e.Row.Cells[i].Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#C1DAD7'");
                e.Row.Cells[i].Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }

            e.Row.Cells[0].Style["cursor"] = "hand";

            if (e.Row.Cells[7].Text == "04")
            { e.Row.Cells[7].Text = "Uren"; }

            if (e.Row.Cells[7].Text == "13")
            { e.Row.Cells[7].Text = "Dagdelen"; }

            HF_RowIndex.Value = String.Empty;
        }
    }

    protected void gv_Functions_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        secure_zk_PGB_Assignment_AddIB_FunctionInputs ucFunc = (secure_zk_PGB_Assignment_AddIB_FunctionInputs)Page.FindControl("firstZZP");

        //List<ViewZTWFunction> pagefuncList = (List<ViewZTWFunction>)ViewState["PageFuncs"];
        List<ViewZTWFunction> pagefuncList = ucFunc.SourceFunctions;

        pagefuncList.RemoveAt(e.RowIndex);

        gv_Functions.DataSource = pagefuncList;
        gv_Functions.DataBind();

        SetFunctionButtons(PanelType.firstP);
        //SetFunctionButtons(PanelType.secondP);

        HF_RowIndex.Value = String.Empty;

        ucFunc.SourceFunctions = pagefuncList;
    }

    private enum PanelType
    {
        firstP,
        secondP
    }

    private void SetFunctionButtons(PanelType type)
    {
        switch (type)
        {
            case PanelType.firstP:
                ((Button)((secure_zk_PGB_Assignment_AddIB_FunctionInputs)Page.FindControl("firstZZP")).FindControl("btn_AddFunc")).Enabled = true;
                ((Button)((secure_zk_PGB_Assignment_AddIB_FunctionInputs)Page.FindControl("firstZZP")).FindControl("btn_UpdateFunc")).Enabled = false;
                break;
            case PanelType.secondP:
                ((Button)((secure_zk_PGB_Assignment_AddIB_FunctionInputs)Page.FindControl("secondZZP")).FindControl("btn_AddFunc")).Enabled = true;
                ((Button)((secure_zk_PGB_Assignment_AddIB_FunctionInputs)Page.FindControl("secondZZP")).FindControl("btn_UpdateFunc")).Enabled = false;
                break;
            default:
                break;
        }
    }

    protected void gv_Functions_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (GridViewRow gv_FuncSRow = ((GridView)sender).SelectedRow)
        {
            SetFunctionButtons(PanelType.firstP);
            //SetFunctionButtons(PanelType.secondP);

            secure_zk_PGB_Assignment_AddIB_FunctionInputs ucFunc = (secure_zk_PGB_Assignment_AddIB_FunctionInputs)Page.FindControl("firstZZP");

            if (new Guid(gv_Functions.DataKeys[gv_FuncSRow.RowIndex].Value.ToString()) == new Guid())
            {
                ucFunc.changeInputStatusSelectedAddingFunc(gv_FuncSRow);
            }
            else
            {
                ucFunc.ChangeStep4InputsStatus(false);
            }
            
            //TODO: Enabled the second ZZP functions
            ((DropDownList)ucFunc.FindControl("ddl_IndicationType")).SelectedValue = gv_FuncSRow.Cells[9].Text;

            foreach (GridViewRow gvr in gv_Functions.Rows)
            {
                foreach (TableCell extc in gvr.Cells)
                {
                    extc.BackColor = gvr.RowIndex != gv_FuncSRow.RowIndex ? System.Drawing.Color.White : System.Drawing.ColorTranslator.FromHtml("#C1DAD7");
                }
            }

            HF_RowIndex.Value = gv_FuncSRow.RowIndex.ToString();
        }
    }
    #endregion

    #region Save datas button Action
    protected void functions_btn_Previous_Click(object sender, EventArgs e)
    {
        LoadStepPage(StepType.Step3);
    }

    protected void functions_btn_Cancel_Click(object sender, EventArgs e)
    {
        gv_Functions.DataSource = ViewState["PageFuncs"];
        gv_Functions.DataBind();

        SetFunctionButtons(PanelType.firstP);
        //SetFunctionButtons(PanelType.secondP);
        secure_zk_PGB_Assignment_AddIB_FunctionInputs ucFunc = new secure_zk_PGB_Assignment_AddIB_FunctionInputs();

        ucFunc.ChangeStep4InputsStatus(true);
        LoadStep4SourceDatas();
    }

    private List<ViewZTWFunction> generatePageFunctions(Indicatiebesluit pageIndication, List<ViewZTWFunction> pageFuncs)
    {
        foreach (ViewZTWFunction ztwF in pageFuncs)
        {
            ztwF.NewZTWFunctionID = Guid.NewGuid();
            ztwF.IndicationID = pageIndication.IndicatiebesluitID;
            ztwF.UpdatedBy = new Guid(nav.User.UserID);
        }

        return pageFuncs;
    }

    private Adres generatePageAdres()
    {
        Adres pAddress = null;

        if (huisnummer.Waarde != String.Empty &&
            postcode.Waarde != String.Empty &&
            straatnaam.Waarde != String.Empty &&
            woonplaats.Waarde != String.Empty)
        {
            pAddress = new Adres();
            pAddress.SoortAdres = new CodelijstGegeven(soortadres.Waarde);

            if (huisnummer.Waarde.Trim().ToString().Length != 0)
            {
                pAddress.Huisnummer = Convert.ToInt32(huisnummer.Waarde.Trim().ToString());
            }

            pAddress.HuisnummerToevoeging = huisnummertoevoeging.Waarde.Trim();
            pAddress.Postcode = postcode.Waarde.Trim();
            pAddress.Straatnaam = straatnaam.Waarde.Trim();
            pAddress.WoonplaatsNaam = woonplaats.Waarde.Trim();
            pAddress.CodeLand = codeland.Waarde.Trim();
            pAddress.Telefoonnummer01 = telefoonnummer1.Waarde.Trim();
        }
        else
        {
            pAddress = (Adres)ViewState["OrignalAddress"];
        }

        return pAddress;
    }

    protected void btn_Save_Click(object sender, EventArgs e)
    {
        if (gv_Functions.Rows.Count > 0)
        {
            Indicatiebesluit pageIndi = (Indicatiebesluit)ViewState["PAGEINDICATION"];
            List<ViewZTWFunction> pageFunc = generatePageFunctions(pageIndi, (List<ViewZTWFunction>)ViewState["PageFuncs"]);

            IBManuallyHandler ibm = new IBManuallyHandler();
            //ibm.processManuallyIBDatas(nav.Client,
            //    generatePageAdres(), (Adres)ViewState["OrignalAddress"],
            //    pageFunc, pageIndi, nav.User.ConnString, nav.User.UserID, nav.User.BestandenDbConnString, nav.User.Zorgkantoorcode, 
            //    nav.User.UserName, false);
        }
    }
    #endregion
}
